<?
// ESTABLISH SORT ORDERS FOR THE EXISTING STUDENT FIELDS
$categories_RET = DBGet(DBQuery("SELECT ID,TITLE,SORT_ORDER FROM STUDENT_FIELD_CATEGORIES ORDER BY SORT_ORDER,TITLE"));

DBQuery("DELETE FROM CUSTOM_FIELDS WHERE TYPE='holder'");
$fields_RET = DBGet(DBQuery("SELECT f.ID,c.ID as CATEGORY_ID,f.TYPE FROM custom_fields f, student_field_categories c WHERE c.ID=f.CATEGORY_ID ORDER BY f.TITLE"),array(),array('CATEGORY_ID','TYPE'));

$types = array('text','numeric','date','select','textarea','multiple','log','radio');
foreach($fields_RET as $category=>$fields)
{
	$first_radio = false;
	$order = 1;
	foreach($types as $type)
	{
		if(count($fields[$type]))
		{
			foreach($fields[$type] as $field)
			{
				if($type=='textarea' || $type=='multiple')
				{
					if($order%3==0)
					{
						DBQuery("INSERT INTO CUSTOM_FIELDS (ID,TYPE,CATEGORY_ID,SORT_ORDER) values(".db_seq_nextval('CUSTOM_SEQ').",'holder','".$field['CATEGORY_ID']."','".$order."')");
						$order++;
					}
				}
				elseif($type=='log' || ($type=='radio' && !$first_radio))
				{
					if(!$first_radio && $type=='radio')
					{
						$first_radio = true;
						
					}
					if($order%3==2)
					{
						DBQuery("INSERT INTO CUSTOM_FIELDS (ID,TYPE,CATEGORY_ID,SORT_ORDER) values(".db_seq_nextval('CUSTOM_SEQ').",'holder','".$field['CATEGORY_ID']."','".$order."')");
						$order++;
						DBQuery("INSERT INTO CUSTOM_FIELDS (ID,TYPE,CATEGORY_ID,SORT_ORDER) values(".db_seq_nextval('CUSTOM_SEQ').",'holder','".$field['CATEGORY_ID']."','".$order."')");
						$order++;
					}
					elseif($order%3==0)
					{
						DBQuery("INSERT INTO CUSTOM_FIELDS (ID,TYPE,CATEGORY_ID,SORT_ORDER) values(".db_seq_nextval('CUSTOM_SEQ').",'holder','".$field['CATEGORY_ID']."','".$order."')");
						$order++;
						if(!$first_radio && $type=='radio')
						{
							$first_radio = true;
						}
					}			
				}
				DBQuery("UPDATE CUSTOM_FIELDS SET SORT_ORDER='$order' WHERE ID='".$field['ID']."'");
				$order++;
			}
		}
	}
}

// EXTRACT EMAIL ADDRESSES FOR CONTACTS AND PLACE THEM IN THE NEW EMAIL ADDRESS FIELD

// MAKE SURE THAT THE NEW STUDENT_GPA_CALCULATED PRIMARY KEY ISN'T VIOLATED

DBQuery("ALTER TABLE LUNCH_PERIOD ADD CONSTRAINT lunch_period_pkey  PRIMARY KEY (STUDENT_ID,SCHOOL_DATE,PERIOD_ID,TABLE_NAME)");

?>